﻿using Microsoft.Extensions.DependencyInjection;
using Modules.System.User;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Entity;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Project.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ProjectGuaranteeIncomeRepository : Repository<ProjectGuaranteeIncome, DefaultDbContext>
    {
        private readonly IApplicationContext applicationContext;

        public ProjectGuaranteeIncomeRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
            this.applicationContext = applicationContext;
        }

        /// <summary>
        /// author:hzj date:2023/12/22 describe:分页获取收入明细
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IPagedList<ProjectGuaranteeIncome> GetProjectGuaranteeIncomes(ProjectGuaranteeIncomeQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("project_guarantee_income");

            #region 主管单位数据权限

            if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator())
            {
                if (deptUser.IsRSAdministrator())
                {
                    sql.InnerJoin("project as prj").On($"project_guarantee_income.project_id=prj.project_id and prj.is_deleted=0  ");
                }
                else
                {
                    sql.InnerJoin("project as prj").On($"project_guarantee_income.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type=@0 ", deptUser.IndustryType);
                }
                if (deptUser.Level == AdministrativeLevel.City)
                    sql.Append($" and prj.city_code={deptUser.CityCode}");
                if (deptUser.Level == AdministrativeLevel.Area)
                    sql.Append($" and prj.area_code={deptUser.AreaCode}");
            }

            #endregion 主管单位数据权限

            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("( code Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.GuaranteePaymentId.HasValue)
                sql.Where("guarantee_payment_id=@0", query.GuaranteePaymentId);
            if (query.ProjectId.HasValue)
                sql.Where("project_guarantee_income.project_id=@0", query.ProjectId);
            sql.OrderBy("project_guarantee_income.create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }
    }
}